<?php

/*
 * 订单脚本执行控制器
 * @author wyb
 */

namespace Shells\Controller;

class OrderController extends BaseController {

    /**
     * 下单后操作30分钟未支付的订单失效
     */
    public function orderAutoInvalid() {
        //查询没有按时间以内支付的订单
        $order_list = M('order')->where(array('pay_status' => array('IN', array('1', '2'), 'status' => 1)))->select();
        foreach ($order_list as $key => $valu) {
            //订单已过期
            if (strtotime($valu['create_time']) + 30 * 60 < time()) {
                //获得过期的子订单信息
                $order_line_list = M('order_line')->where(array('order_id' => $valu['id']))->group('supply_customer_id')->select();
                foreach ($order_line_list as $k => $v) {
                    //锁库订单库存回滚
                    if ($v['source_type'] == 1) {
                        M('goods_distribution')->where(array('id' => $v['distribution_product_id']))->setInc('stock_num', $v['num']);
                    } else { //共享库存回滚
                        M('goods_supply')->where(array('id' => $v['supply_product_id']))->setInc('stock_num', $v['num']);
                        //更新商品热度值
                        hotSortNumSave(M('goods_supply')->where(array('id' => $v['supply_product_id']))->getField('goods_id'));
                    }
                    //共享仓库锁库库存减少
                    M('goods_supply')->where(array('id' => $v['supply_product_id']))->setDec('lock_stock_num', $v['num']);
                    //判断已支付则需要自动退款
                    if ($v['pay_status'] == '1' && $v['pay_money'] > 0) {
                        $object_name = '\\Api\\Extend\\Payment\\' . ucfirst($v['pay_type']);
                        $config = D('Common/PaymentConfig')->getSettingConfig($v['payment_id'], $pay_type);
                        $object = new $object_name($config);
                        $result = $object->orderRefund( array('ref' => $v['ref']), $v['pay_money'] );
                        if( $result['status'] === true ) {
                            M('order_line')->where(array('id' => $v['id']))->save(array('pay_status' => 3)); //退款成功
                        } else {
                            M('order_line')->where(array('id' => $v['id']))->save(array('pay_status' => 2)); //退款失败
                        }
                    }
                }
                //订单设置为失效
                M('order')->where(array('id' => $valu['id']))->save(array('status' => 2));
                //推送系统消息
                M('system_message')->add(array(
                    'role' => 1,
                    'target_id' => $valu['distribution_customer_id'],
                    'title' => '订单30分钟之内未支付自动失效',
                    'content' => '尊敬的【' . M('customer')->where(array('id' => $valu['distribution_customer_id']))->getField('shop_name') . '】您好，您的订单编号【' . $valu['ref'] . '】由于30分钟内未全部支付，现已失效。如有支付一部分订单则支付金额已原路返回，请及时查验。',
                    'create_time' => date('Y-m-d H:i:s')
                ));
            }
        }
    }

}
